/*
 * Project it.battlehorse.rcp.tools.dbbase
 * Created on Nov 25, 2005
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * A copy of the LGPL is available also at
 * http://www.gnu.org/copyleft/lesser.html
 * 
 */ 
package it.battlehorse.rcp.tools.dbbase.test;

import it.battlehorse.rcp.sl.annot.Injected;
import it.battlehorse.rcp.sl.annot.Serviceable;
import it.battlehorse.rcp.tools.dbbase.DatasourceConfig;
import it.battlehorse.rcp.tools.dbbase.IDbManager;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;

/**
 * Performs a connection test to the datasource given at construction time
 * 
 * @author battlehorse
 * @since Nov 25, 2005
 */
@Serviceable
public class ConnectionTester implements Callable<Boolean> {
	
	/* a logger */
	private Log log;
	
	/* a database manager */
	private IDbManager dbManager;
	
	/**
	 * Injects a logger into this object
	 * 
	 * @param log a logger
	 */
	@Injected
	public void setLog(Log log) {
		this.log = log;
	}
	
	/**
	 * Injects a db manager into this object
	 * 
	 * @param manager a db manager
	 */
	@Injected
	public void setDbManager(IDbManager manager) {
		this.dbManager = manager;
	}
	
	private DatasourceConfig cfg;
	
	/**
	 * Creates a new instance of the class
	 * 
	 * @param ds the datasource to be tested
	 */
	
	public ConnectionTester(DatasourceConfig cfg) {
		this.cfg = cfg;
	}

	/* (non-Javadoc)
	 * @see java.util.concurrent.Callable#call()
	 */
	public Boolean call() throws Exception {		
		boolean testOk = true;		
		
		BasicDataSource ds  = null;
		try {
			ds = (BasicDataSource) dbManager.getDataSource(cfg,false);
			
		}		
		catch(Exception e) {
			log.error(e.getMessage(),e);
		}
		
		Connection con = null;
		try {
			if (ds != null)
				con = ds.getConnection();					
		}
		catch(final SQLException sqle) {	
			testOk = false;
			
			if (log.isTraceEnabled())
				log.trace("The connection test failed : " + sqle.getMessage(),sqle);
			Display.getDefault().asyncExec(new Runnable() {
				
				public void run() {
					MessageDialog.openError(
							PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
							"Connection Error!",
							"The connection test failed: \n" +
							sqle.getMessage() + "\n" + 
							"SQLCode: " + sqle.getErrorCode());
				}
			});
		}
		finally {
			try {
				if (con != null)
					con.close();
			}
			catch(SQLException sqle) {}
			
			try {
				if (ds != null) ds.close();
			}
			catch(SQLException sqle) {}
				
		}
		
		if (testOk) {
			if (log.isTraceEnabled())
				log.trace("The connection test completed succesfully");
			
			Display.getDefault().asyncExec(new Runnable() {
				
				public void run() {
					MessageDialog.openInformation(
							PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
							"Connection successful!",
							"The connection test has completed successfully");
				}
			});
		}
			
		return testOk;
	}

}
